﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using TopoMap.Ign.DAO.IGNtilesDataSetTableAdapters;
using TopoMap.Ign.DAO;

namespace GpSpotMe.Ign.TileModel
{
    public static class TileManager
    {
        private static IGN25TableAdapter ing25TA = new IGN25TableAdapter();
        private static string uri = "http://ts0.iberpix.ign.es/tileserver/n=mapa_mtn25;z=30;r=4000;i={0};j={1}.jpg";
        
        public static Tile GetTile(int i, int j)
        {
            Bitmap bmp = null;
            try
            {
                IGNtilesDataSet.IGN25DataTable dtIGN25 = ing25TA.GetDataByCoord(i, j);
                if (dtIGN25.Rows.Count == 0)
                {
                    System.Uri uriIgn = new Uri(string.Format(uri, i, j));
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriIgn.AbsoluteUri);
                    request.Timeout = 30000;
                    bmp = new Bitmap(request.GetResponse().GetResponseStream());

                    IGNtilesDataSet.IGN25Row tr = dtIGN25.NewIGN25Row();
                    tr.COORD_X = i;
                    tr.COORD_Y = j;

                    using (MemoryStream ms = new MemoryStream())
                    {
                        bmp.Save(ms, ImageFormat.Jpeg);
                        byte[] bitmapData = ms.ToArray();
                        tr.TILE = bitmapData;
                    }
                    dtIGN25.AddIGN25Row(tr);
                    ing25TA.Update(dtIGN25);
                    
                }
                else
                {
                    using (MemoryStream ms = new MemoryStream(dtIGN25[0].TILE))
                    {
                        bmp = new Bitmap(ms);
                    }
                }
            }
            catch(Exception e)
            {
                bmp = new Bitmap(256, 256);
                using (Graphics errorGraphics = Graphics.FromImage(bmp))
                {
                    errorGraphics.FillRectangle(new SolidBrush(Color.Coral), 0, 0, bmp.Width, bmp.Height);
                    Brush myBrush = new SolidBrush(Color.Red);
                    Font myFont = new Font(FontFamily.GenericSansSerif, 8, FontStyle.Regular);
                    //errorGraphics.DrawString(e.Message, myFont, myBrush, 5, 20);
                    RectangleF layoutRectangle = new RectangleF(1,1,254,254);
                    errorGraphics.DrawString(e.Message, myFont, myBrush, layoutRectangle);
                }
            }
            return new Tile(i, j, bmp);
        }

//        private Bitmap GetTileDirect(int i, int j)
//        {
//            Bitmap bmp = null;
//            string providerName = ConfigurationManager.ConnectionStrings["DirectIGNTilesConnection"].ProviderName;
//            string connectionString = ConfigurationManager.ConnectionStrings["DirectIGNTilesConnection"].ConnectionString;

//            DbProviderFactory factory = DbProviderFactories.GetFactory(providerName);
//            using (DbConnection connection = factory.CreateConnection())
//            {
//                connection.ConnectionString = connectionString;
//                connection.Open();
//                using (DbCommand command = factory.CreateCommand())
//                {
//                    command.Connection = connection;
//                    command.CommandType = CommandType.Text;
//                    command.CommandText =
//                        @"SELECT     COORD_X, COORD_Y, TILE
//                            FROM         IGN25
//                            WHERE     (COORD_X = @i) AND (COORD_Y = @j)";
//                    DbParameter p1 = command.CreateParameter();
//                    p1.ParameterName = "i";
//                    p1.Value = i;
//                    command.Parameters.Add(p1);
//                    DbParameter p2 = command.CreateParameter();
//                    p2.ParameterName = "j";
//                    p2.Value = j;
//                    command.Parameters.Add(p2);

//                    using (DbDataReader reader = command.ExecuteReader())
//                    {
//                        if (reader.Read())
//                        {
//                            int x = (int)reader["COORD_X"];
//                            int y = (int)reader["COORD_y"];
//                            byte[] tile = (byte[])reader["TILE"];
//                            using (MemoryStream ms = new MemoryStream(tile))
//                            {
//                                bmp = (Bitmap)Bitmap.FromStream(ms);
//                            }
//                        }
//                    }
//                }
//            }

//            return bmp;
//        }
    }
}
